package com.arcgis.app;

import android.content.ContentValues;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.arcgis.app.RecyclerView.InputSpacesItemDecoration;
import com.arcgis.app.adapter.SelectPictureAdapter;
import com.arcgis.app.dao.PointInfoDao;
import com.arcgis.app.utils.RealPathFromUriUtils;
import com.arcgis.app.utils.Urls;
import com.arcgis.app.view.CommonHeaderView;
import com.arcgis.app.view.CommonSectionHeader;
import com.kaopiz.kprogresshud.KProgressHUD;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;

import butterknife.BindView;
import butterknife.ButterKnife;

import static com.arcgis.app.utils.Urls.URL_IMAGE;
import static com.arcgis.app.utils.Urls.URL_Submit;
import static com.arcgis.app.utils.Urls.URL_UPLOAD;

public class PointInputActivity extends AppCompatActivity {
    @BindView(R.id.currentLocationText)
    EditText currentLocation;
    @BindView(R.id.longtitudeText)
    EditText longtitudeText;
    @BindView(R.id.latitudeText)
    EditText latitudeText;
    @BindView(R.id.idCardText)
    EditText idCard;
    @BindView(R.id.phoneNumberText)
    EditText phonenumber;
    //    @BindView(R.id.addImageView)
//    ImageView imageView;
    @BindView(R.id.submitBtn)
    Button submitBtn;
    @BindView(R.id.input_recyclerView)
    RecyclerView inputRecyclerView;
    @BindView(R.id.cs_section_fj)
    CommonSectionHeader csSectionFj;
    @BindView(R.id.input_header_attr)
    CommonSectionHeader inputHeaderAttr;
    @BindView(R.id.header)
    CommonHeaderView header;
    @BindView(R.id.lv_longitude)
    LinearLayout lvLongitude;
    @BindView(R.id.lv_latitude)
    LinearLayout lvLatitude;
    @BindView(R.id.input_imageNum)
    TextView inputImageNum;
    private PointInfoDao point;
    double longtitude;
    double latitude;
    public ArrayList<String> photoList;
    public ArrayList<File> fileList;
    public SelectPictureAdapter adapter;
    private Handler mHandler;
    public Uri photoUri;
    private KProgressHUD hud;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        supportRequestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.input_layout_main);
        ButterKnife.bind(this);
//        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);

        final Intent intent = getIntent();
        photoList = new ArrayList<String>();
        fileList = new ArrayList<File>();
        new MyThread().start();

        header.setMiddleTitle("新建消息");
        inputHeaderAttr.setLeftTitle("业务属性");
        csSectionFj.setLeftTitle("业务附件");

        point = (PointInfoDao) intent.getSerializableExtra("point");
        if (point != null) {
            if (point.admin == 1 || point.admin == 2) {
                lvLatitude.setVisibility(View.GONE);
                lvLongitude.setVisibility(View.GONE);
                longtitudeText.setText("");
                latitudeText.setText("");
                phonenumber.setText(point.phonenumber);
                idCard.setText(point.idCard);
                currentLocation.setText(point.currentLocation);

            } else {
                longtitudeText.setText(String.valueOf(point.longtitude));
                latitudeText.setText(String.valueOf(point.latitude));
                phonenumber.setText(point.phonenumber);
                idCard.setText(point.idCard);
                currentLocation.setText(point.currentLocation);
            }
            if (point.getId() > 0){
                header.setMiddleTitle("查看消息");
            }
        } else {
            longtitude = intent.getDoubleExtra("longtitude", 0.0f);
            latitude = intent.getDoubleExtra("latitude", 0.0f);

            longtitudeText.setText(String.valueOf(longtitude));
            latitudeText.setText(String.valueOf(latitude));

            point = new PointInfoDao();
            point.setLongtitude(longtitude);
            point.setLatitude(latitude);
        }

        if (point.getFilepath() != null  && point.getFilepath().size() > 0){
           for(int i = 0;i<point.getFilepath().size();i++){
               String url = URL_IMAGE + File.separator + point.getFilepath().get(i);
               photoList.add(url);
               onDataChanged();
           }
        }

        GridLayoutManager gridLayoutManager
                = new GridLayoutManager(this, 5);
//        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        inputRecyclerView.setLayoutManager(gridLayoutManager);
        int space = 10;
        inputRecyclerView.addItemDecoration(new InputSpacesItemDecoration(space));
        adapter = new SelectPictureAdapter(this, photoList);
        adapter.setonItemClickListener(new SelectPictureAdapter.OnItemClick() {
            @Override
            public void onItemClick(int position) {
                selectPhoto();
            }
        });
        adapter.setOnCloseImageClick(new SelectPictureAdapter.OnCloseImageClick() {
            @Override
            public void onCloseImageClick(int position) {
                fileList.remove(position);
                photoList.remove(position);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        adapter.notifyDataSetChanged();
                        onDataChanged();
                    }
                });

            }
        });
        inputRecyclerView.setAdapter(adapter);
        new MyThread().start();

        submitBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (currentLocation.getText().length() == 0) {
                    Toast.makeText(PointInputActivity.this, "请输入当前位置", Toast.LENGTH_SHORT).show();
                    return;
                }

                if (idCard.getText().length() != 18) {
                    Toast.makeText(PointInputActivity.this, "请输入正确的身份证号码", Toast.LENGTH_SHORT).show();
                    return;
                }

                if (phonenumber.getText().length() != 11) {
                    Toast.makeText(PointInputActivity.this, "请输入正确的手机号码", Toast.LENGTH_SHORT).show();
                    return;
                }

                boolean hasFiles = fileList.size() > 0 ? true : false;

                if(point.getId() > 0){
                    finish();
                    return;
                }

                hud =KProgressHUD.create(PointInputActivity.this)
                        .setStyle(KProgressHUD.Style.SPIN_INDETERMINATE)
                        .setLabel("请稍等...")
                        .setDetailsLabel("正在上传")
                        .setCancellable(false)
                        .setAnimationSpeed(2)
                        .setDimAmount(0.5f)
                        .show();

////                String url = Constants.USER_NET_ICON;
                OkGo.<String>post(URL_Submit)
                        .params("longtitude", point.longtitude)
                        .params("latitude", point.latitude)
                        .params("phonenumber", phonenumber.getText().toString())
                        .params("idCard", idCard.getText().toString())
                        .params("currentLocation", currentLocation.getText().toString())
                        .params("geometry", point.getGeometry())
                        .params("admin", point.admin)
                        .addFileParams("files", fileList)
                        .isMultipart(hasFiles)
                        .tag(this)
                        .execute(new StringCallback() {
                            @Override
                            public void onSuccess(Response<String> response) {
                                Log.i("get", response.body());
                                point.setIdCard(idCard.getText().toString().trim());
                                point.setPhonenumber(phonenumber.getText().toString().trim());
                                point.setCurrentLocation(currentLocation.getText().toString().trim());

                                Intent intent1 = new Intent();

                                Bundle bundle = new Bundle();

                                bundle.putSerializable("point", point);
                                intent1.putExtras(bundle);
//                                intent.putExtra("point",point);
//                                startActivity(intent1);
                                //参数回传
                                setResult(1001, intent1);


                            }

                            @Override
                            public void onError(Response<String> response) {
                                Log.i("get", response.body());
                                super.onError(response);
                            }

                            @Override
                            public void onFinish() {
                                scheduleDismiss();
                                Toast.makeText(PointInputActivity.this, "上传成功", Toast.LENGTH_SHORT).show();
                                finish();
                                super.onFinish();
                            }
                        });
            }
        });


    }

    class MyThread extends Thread {
        @Override
        public void run() {
            Looper.prepare();
            mHandler = new Handler() {
                @Override
                public void handleMessage(@NonNull Message msg) {
                    super.handleMessage(msg);
                    String realPathFromUri1 = "";
                    if (msg.what == 1){
                        Intent data = (Intent) msg.obj;
                        realPathFromUri1 = RealPathFromUriUtils.getRealPathFromUri(PointInputActivity.this, data.getData());
                    }else if(msg.what == 0){
                        Uri uri = (Uri) msg.obj;
                        realPathFromUri1 = RealPathFromUriUtils.getRealPathFromUri(PointInputActivity.this, uri);
                    }

                    photoList.add(realPathFromUri1);
                    File file = new File(realPathFromUri1);
                    fileList.add(file);
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            adapter.notifyDataSetChanged();
                            onDataChanged();
                        }
                    });
//                Bundle bundle = data.getExtras(); // 从data中取出传递回来缩略图的信息，图片质量差，适合传递小图片
//                Bitmap bitmap = (Bitmap) bundle.get("data"); // 将data中的信息流解析为Bitmap类型
//                photoList.add(bitmap);

                }
            };
            Looper.loop();
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case 100:

                if (resultCode == RESULT_OK) {
//                    if (data != null) {
//                        Uri uri = data.getData();
//                        if (uri != null) {
//                            String realPathFromUri1 = RealPathFromUriUtils.getRealPathFromUri(PointInputActivity.this, data.getData());
//                            Toast.makeText(PointInputActivity.this, "有数据", Toast.LENGTH_LONG).show();
//                        } else {
//                            if (uri == null) {
//                                if (photoUri != null) {
//                                    uri = photoUri;
//                                }
//                            }
//
//                        }

                        Message message = new Message();
                        message.what = 0;
                        message.obj = photoUri;
                        mHandler.sendMessage(message);
//                    }
                }
                break;
            case 101:
                Message message = new Message();
                message.what = 1;
                message.obj = data;
                mHandler.sendMessage(message);

                break;
        }
    }

    public void selectPhoto() {
        final String[] gender = new String[]{"拍照", "从图库选择"};
        final AlertDialog.Builder builder = new AlertDialog.Builder(PointInputActivity.this);
        builder.setTitle("请选择");
        builder.setItems(gender, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                Toast.makeText(PointInputActivity.this, "点击了一下" + which, Toast.LENGTH_SHORT).show();
                switch (which) {
                    case 0:
                        openCamera();
                        break;
                    case 1:
                        openPhotoLib();
                        break;
                }
            }

        });

        builder.create().show();
    }

    public void openCamera() {
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);  //跳转到 ACTION_IMAGE_CAPTURE
        //判断内存卡是否可用，可用的话就进行存储
        //putExtra：取值，Uri.fromFile：传一个拍照所得到的文件，fileImg.jpg：文件名
//        intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(Environment.getExternalStorageDirectory(),"fileImg.jpg")));
        SimpleDateFormat timeStampFormat = new SimpleDateFormat(
                "yyyy_MM_dd_HH_mm_ss");
        String filename = timeStampFormat.format(new Date());
        ContentValues values = new ContentValues();
        values.put(MediaStore.Audio.Media.TITLE, filename);

        photoUri = getContentResolver().insert(
                MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);

        intent.putExtra(MediaStore.EXTRA_OUTPUT, photoUri);
        startActivityForResult(intent, 100);
    }

    public void openPhotoLib() {
        Intent intent1 = new Intent(Intent.ACTION_PICK);
        intent1.setType("image/*");
        startActivityForResult(intent1, 101);
    }



    private void saveToInternet(String filesDir, String fileName) {
        //上传单个文件
//        File file = new File(filesDir, fileName);
        File file = new File(filesDir);
        if (file.exists()) {
            OkGo.<String>post(Urls.URL_UPLOAD)
                    .tag(this)
                    .params("file", file)
                    .isMultipart(true)
                    .execute(new StringCallback() {
                        @Override
                        public void onSuccess(Response<String> response) {
                            Log.i("upload success: ", response.body() + ",code: " + response.code());
                            Toast.makeText(PointInputActivity.this, "上传成功", Toast.LENGTH_SHORT).show();
                        }

                        @Override
                        public void onError(Response<String> response) {
                            Log.i("upload failed: ", response.body() + ",code: " + response.code());
                            Toast.makeText(PointInputActivity.this, "上传失败", Toast.LENGTH_SHORT).show();
                        }
                    });
        }
    }

    public void onDataChanged(){
        if (photoList != null){
            inputImageNum.setText( photoList.size()+ "/5");
        }else{
            inputImageNum.setText("0/5");
        }
    }


    private void scheduleDismiss() {
        Handler handler = new Handler();
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                hud.dismiss();
            }
        }, 2000);
    }

}
